package db.exchange.client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import db.exchange.market.ExchangeEngine;
import db.exchange.message.Order;

//import message.Type;

public class SocketWriter implements Runnable {
	private static final Logger LOG = LogManager.getLogger(ExchangeEngine.class
			.getName());

	private String loginName;
	private Socket socket;
	private ObjectOutputStream out;
	private Transport transport;
	
	public SocketWriter(Socket socket, String loginName) {
		super();
		this.socket = socket;
		this.loginName = loginName;
		
	}


	@Override
	public void run() {

		try {
			out = new ObjectOutputStream(socket.getOutputStream());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		sendLogin(loginName);

		waitGuiQueueForOrders();
		// sendNewOrders();

	}

	private void waitGuiQueueForOrders() {
		try {
			while (true) {

				Order o = transport.outQueue.take();
				sendMessage(order2String(o));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void sendLogin(String loginName) {
		sendMessage("35=A|39="+loginName); // A-login | 39=sender id
	}

	public void sendOrder(Order o) {
		sendMessage(order2String(o));
	}

	public String order2String(Order o) {
		StringBuilder row = new StringBuilder("35=D");
		row.append("|11=" + o.getOrderId());
		row.append("|55=" + o.getSymbol());
		row.append("|54=" + o.getOperation());
		row.append("|44=" + o.getPrice());
		row.append("|38=" + o.getQty());
		row.append("|40=2");

		return row.toString();

	}

	private void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			out.reset();
			System.out.println("OUT: " + msg);
		} catch (SocketException e) {
			System.out.println("Server Closed the Connection, stop client");
			System.exit(1);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

}
